package org.apiframe.verticle;

import cn.hutool.log.StaticLog;
import cn.hutool.setting.Setting;
import org.apiframe.handler.ApiHandler;
import org.apiframe.utils.ClassLoaderUtils;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.ext.web.Router;

public class ReflectionVerticle extends AbstractVerticle
{

    @Override
    public void start() {
        HttpServer server = vertx.createHttpServer();

        //反射api
        Router router = Router.router(vertx);
        router.route("/api").handler(routingContext -> {
            // 所有的请求都会调用这个处理器处理
            HttpServerResponse response = routingContext.response();

            response.putHeader("Content-Type", "text/html;charset=UTF-8");

            // 写入响应并结束处理
            response.end(ApiHandler.invoke(routingContext.request()));

        });

        //重新加载jar包
        router.route(HttpMethod.GET, "/reload").handler(routingContext -> {
            // 所有的请求都会调用这个处理器处理
            HttpServerResponse response = routingContext.response();

            response.putHeader("Content-Type", "text/html;charset=UTF-8");
            ClassLoaderUtils.reloadClassLoader();
            // 写入响应并结束处理
            response.end("重载成功");

        });

        Setting setting = new Setting("application.properties");
        String port = setting.get("port");
        String version =  setting.get("version");
        server.requestHandler(router::accept).listen(Integer.valueOf(port));
        StaticLog.info(">>>>>>>>>>>>>ApiFrame"+version+"<<<<<<<<<<<<<<");
        StaticLog.info(">>>>>>>>>>>>>启动成功:端口"+port+"<<<<<<<<<<<<<<");
        StaticLog.info(">>>>>>>>>>>>>插件路径:"+ClassLoaderUtils.path+"<<<<<<<<<<<<<<");
    }

    @Override
    public void stop() {
        StaticLog.info(">>>>>>>>>>>>>服务已停止<<<<<<<<<<<<<<");
    }

}
